import dayjs from "dayjs";
import { message } from "@/utils/message";
import {ElMessage, ElMessageBox, Sort} from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  ReportListCommand,
  getReportListApi,
  exportReportExcelApi,
  deleteReportApi,
  AddReportCommand,
  UpdateReportCommand
} from "@/api/airport/safetyManage/report.api";


export function useReportHook() {
  const defaultSort: Sort = {
    prop: "discoveryDate",
    order: "descending"
  };
  const pagination: PaginationProps = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  };

  const statusMap = {
    "0": { text: "待接收", type: "info" },
    "1": { text: "待建模", type: "warning" },
    "2": { text: "已关闭", type: "success" },
    "3": { text: "已建模-问题待提交", type: "primary" },
    "4": { text: "已建模-已提交问题", type: "success" },
    "5": { text: "未建模-已提交问题", type: "success" }

  };

  const timeRange = computed<[string, string] | null>({
    get() {
      if (searchFormParams.beginTime && searchFormParams.endTime) {
        return [searchFormParams.beginTime, searchFormParams.endTime];
      } else {
        return null;
      }
    },
    set(v) {
      if (v?.length === 2) {
        searchFormParams.beginTime = dayjs(v[0]).format('YYYY-MM-DD'); // 格式化日期
        searchFormParams.endTime = dayjs(v[1]).format('YYYY-MM-DD'); // 格式化日期
      } else {
        searchFormParams.beginTime = undefined;
        searchFormParams.endTime = undefined;
      }
    }
  });

  // 定义初始的搜索表单参数
// 定义初始的搜索表单参数（修复部分）
  const initialSearchFormParams = {
    title: '',
    infoSource: '',
    dutyDeptId: undefined,
    status: '0',
    discoverUserName: '',
    discoveryDate: undefined,
    // 添加时间范围字段重置
    beginTime: undefined,
    endTime: undefined
  };

  const searchFormParams = reactive<ReportListCommand>({
    title: "",
    reportType: "",
    terminalType: "",
    discoveryDate: undefined,
    acceptDeptId: undefined,
    infoSource: undefined,
    deptName: undefined,
    status: '0',
    discoverUserName: undefined,
    dutyDeptId: undefined,
    reportId: undefined, // 添加reportId查询参数
  });

  const dataList = ref([]);
  const pageLoading = ref(true);
  const multipleSelection = ref([]);
  const sortState = ref<Sort>(defaultSort);

  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "主题",
      prop: "title",
      minWidth: 150
    },
    {
      label: "信息来源",
      prop: "infoSource",
      minWidth: 100,
      formatter: ({ infoSource }) => {
        const infoSourceMap = {
          "1": "风险识别",
          "2": "隐患排查",
          "3": "安全质量检查",
          "4": "安全专项检查",
          "5": "法定自查",
          "6": "自愿报告",
          "7": "安全预警",
          "8": "应急案例",
          "9": "通知公告",
          "10": "审核审计",
          "11": "外部检查"
        };
        return infoSourceMap[infoSource] || infoSource;
      }
    },
    {
      label: "责任单位",
      prop: "deptName",
      minWidth: 100
    },

    {
      label: "处理单位",
      prop: "dealDeptName",
      minWidth: 100
    },
    {
      label: "详细描述",
      minWidth: 400,
      slot: "infoDescribe" // 指定插槽名称
    },
    // 添加关联整改通知列
    {
      label: "关联的整改通知",
      minWidth: 180,
      slot: "relatedReformCode"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 140,
      formatter: ({ status }) => {
        const statusInfo = statusMap[status] || { text: "未知状态", type: "info" };
        return `<el-tag type="${statusInfo.type}" effect="plain">${statusInfo.text}</el-tag>`;
      },
      cellRenderer: ({ row }) => {
        const statusInfo = statusMap[row.status] || { text: "未知状态", type: "info" };
        return (
          <el-tag size="large" type={statusInfo.type} effect="plain">
            {statusInfo.text}
          </el-tag>
        );
      }
    },
    {
      label: "报告人",
      prop: "discoverUserName",
      minWidth: 80
    },

    {
      label: "接收人",
      prop: "updaterBy",
      minWidth: 80
    },
    {
      label: "发现时间",
      minWidth: 160,
      prop: "discoveryDate",
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "发现地点",
      minWidth: 120,
      prop: "discoveryPlace",
      formatter: ({ discoveryPlace, deptName }) =>
        discoveryPlace || deptName
    },



    {
      label: "操作",
      fixed: "right",
      width: 400,
      slot: "operation"
    }
  ];

  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    pagination.currentPage = 1;
    getReportList();
  }

  async function onSearch(tableRef) {
    // 重置排序
    sortState.value = defaultSort;
    // 重置分页
    pagination.currentPage = 1;
    // 重新查询数据
    await getReportList();
  }

  function resetForm(formEl, tableRef) {
    // 直接重置搜索表单参数为初始值
    Object.assign(searchFormParams, initialSearchFormParams);
    // 执行搜索操作刷新列表
    onSearch(tableRef);
  }

  async function getReportList() {
    pageLoading.value = true;
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    const { data } = await getReportListApi(toRaw(searchFormParams)).finally(
      () => {
        pageLoading.value = false;
      }
    );
    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function exportAllExcel() {
    if (sortState.value != null) {
      CommonUtils.fillSortParams(searchFormParams, sortState.value);
    }
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    CommonUtils.fillTimeRangeParams(searchFormParams, timeRange.value);

    exportReportExcelApi(toRaw(searchFormParams), "安全信息数据.xlsx");
  }

  async function handleDelete(row) {
    await deleteReportApi([row.reportId]).then(() => {
      message(`您删除了编号为${row.reportId}的这条安全信息`, {
        type: "success"
      });
      getReportList();
    });
  }




  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的安全信息吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await deleteReportApi(multipleSelection.value).then(() => {
          message(`您删除了编号为[ ${multipleSelection.value} ]的安全信息`, {
            type: "success"
          });
          getReportList();
        });
      })
      .catch(() => {
        message("取消删除", {
          type: "info"
        });
        tableRef.getTableRef().clearSelection();
      });
  }


  // 关联已有模型方法，目前为空
  const linkExistingModel = (row: any) => {
    // 可在此添加关联已有模型的具体逻辑
  };

  // 风险建模方法，目前为空
  const riskModeling = (row: any) => {
    // 可在此添加风险建模的具体逻辑
  };

  function decodeBase64(base64Str: string): string {
    try {
      return decodeURIComponent(
        atob(base64Str)
          .split("")
          .map(function (c) {
            return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
          })
          .join("")
      );
    } catch (err) {
      return "<p>内容解析失败</p>";
    }
  }

  function decodeBase64withoutLab(base64Str: string): string {
    try {
      // 先解码Base64，再处理UTF-8编码
      const decoded = decodeURIComponent(
        atob(base64Str)
          .split("")
          .map(function (c) {
            return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
          })
          .join("")
      );

      // 1. 将所有img标签替换为"《点击查看图片》"
      // 2. 移除所有其他HTML标签
      return decoded
        .replace(/<img[^>]*>/gi, '《点击查看图片》')  // 替换img标签
        .replace(/<[^>]+>/g, '');  // 移除剩余HTML标签
    } catch (err) {
      console.error('Base64解码失败:', err);
      return '';
    }
  }
  onMounted(getReportList);

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    timeRange,
    handleBulkDelete,
    // 导出新增方法
    linkExistingModel,
    riskModeling,
    multipleSelection,
    onSearch,
    onSortChanged,
    exportAllExcel,
    getReportList,
    resetForm,
    handleDelete,
    decodeBase64,
    decodeBase64withoutLab
  };
}
